<?php

namespace app\files\controller;

use think\Request;
use think\Response;

/**
 * 通用文件处理
 */
class Music {

    protected $request;
    protected $config;

    public function __construct(Request $request) {
        $this->request = $request;
        $this->config = config('upload_audio');
    }

    /**
     * 输出返回数据
     * @access protected
     * @param mixed     $data 要返回的数据
     * @param String    $type 返回类型 JSON XML
     * @param integer   $code HTTP状态码
     * @return Response
     */
    protected function response($msg, $code = 200, $data = '', $type = 'json') {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            '_link' => '',
        ];
        if ($data) {
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $result['_link'][] = getFileUrl($value, 'file');
                }
            } else {
                $result['_link'] = getFileUrl($data, 'file');
            }
        }
        $header = ['x_end_time' => $this->request->time()];

        $response = Response::create($result, $type)->code($code)->header($header);
        throw new \think\exception\HttpResponseException($response);
    }

    /**
     * 文件下载
     *
     * @return \think\Response
     */
    public function index($sha1, $type = 128) {
        $info = db('file')->where('sha1', $sha1)->find();
        if (empty($info)) {
            return $this->response('指定文件不存在!', 404);
        }
        $path = './.' . $info['path'];
        if (!is_file($path)) {
            return $this->response('指定文件已被系统删除!', 404);
        }
        $temp = './../runtime/music/' . substr($sha1, 0, 2) . DS . $type . '_' . $sha1 . '.' . $info['ext'];
       
        if (is_file($temp)) {
            $path = $temp;
        } else {
            if (!is_dir(ROOT_PATH . '/runtime/music/' . substr($sha1, 0, 2) . DS)) {
                mkdir(ROOT_PATH . '/runtime/music/' . substr($sha1, 0, 2) . DS, 0755, true);
            }
            $temp = ROOT_PATH . str_replace('./../', '', $temp);
          
            ffmpeg(ROOT_PATH . str_replace('./../', '', $path), $temp); //压缩mp3    
        }
        header("Location:" . $path);
        exit();
    }

    /**
     * 文件下载
     *
     * @return \think\Response
     */
    public function download($sha1) {
        $info = db('file')->where('sha1', $sha1)->find();
        if (empty($info)) {
            return $this->response('指定文件不存在!', 404);
        }
        $path = './.' . $info['path'];
        if (!is_file($path)) {
            return $this->response('指定文件已被系统删除!', 404);
        }
        $content = file_get_contents($path);
        $header['Content-Length'] = $info['size'];
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
            //for IE
            $header['Content-Disposition'] = 'attachment; filename="' . rawurlencode(time() . '.' . $info['ext']) . '"';
        } else {
            $header['Content-Disposition'] = 'attachment; filename="' . time() . '.' . $info['ext'] . '"';
        }
        return response($content, 200, $header)->contentType($info['mime']);
    }

    /**
     * 文件上传
     */
    public function upload() {

        $files = $this->request->file($this->config['name']);
        if (empty($files)) {
            return $this->response('没有上传的文件!', 400);
        }
        // $type = $this->request->param('type', 'single');
        // if ($type == 'multi') {
        //     return $this->multi($files);
        // } else {
        return $this->single($files);
        // }
    }

    /**
     * 单文件上传
     * @param type $file file对象
     * @return type
     */
    private function single($file) {
        if (is_array($file)) {
            $file = current($file);
        }
        if ($file->check($this->config['rule']) === false) {
            return $this->response($file->getMime() . $file->getError() . $this->config['rule']['type'], 400);
        }
        $info = db('file')->where('sha1', $file->hash())->find();
        if (empty($info)) {
            $res = $file->rule($this->config['savename'])->move(ROOT_PATH . $this->config['path']);
            if ($res === false) {
                return $this->response($file->getError(), 400);
            }
            $path = $this->config['path'] . $res->getSaveName();
            $getid3 = $this->getid3(ROOT_PATH . $path); //分析文件

            if (in_array($getid3['mime_type'], $this->config['mime_type'])) {
                $info = [
                    'path' => $path,
                    'create_time' => $this->request->time(),
                    'sha1' => $res->hash(),
                    'size' => $getid3['filesize'],
                    'mime' => $getid3['mime_type'],
                    'ext' => $getid3['fileformat'],
                    'playtime' => $getid3['playtime_string'],
                ];
                db('file')->insert($info);
                //压缩mp3
                $temp_path = $this->config['temp_path'] . DS . substr($res->hash(), 0, 2);
                mkdirs($temp_path); //创建目录
                $temp_paths = $temp_path . DS . '128_' . $res->hash() . '.mp3'; //压缩输出完整根路径
                ffmpeg($path, $temp_paths); //压缩mp3
            } else {
                return $this->response('上传音频类型错误!', 400);
            }
        }

        return $this->response('上传成功!', 200, $file->hash());
    }

    /**
     * 多文件上传
     * @param type $files file对象集合
     * @return type
     */
    // private function multi($files)
    // {
    //     if (!is_array($files)) {
    //         $files = [$files];
    //     }
    //     $savedata = [];
    //     $data     = [];
    //     foreach ($files as $file) {
    //         if ($file->check($this->config['rule']) === false) {
    //             return $this->response($file->getError(), 400);
    //         }
    //         $info = db('picture')->where('sha1', $file->hash())->find();
    //         if (empty($info)) {
    //             $res = $file->rule($this->config['savename'])->move(ROOT_PATH . $this->config['path']);
    //             if ($res === false) {
    //                 return $this->response($file->getError(), 400);
    //             }
    //             $path       = $this->config['path'] . $res->getSaveName();
    //             $getid3     = $this->getid3(ROOT_PATH . $path); //分析文件
    //             $savedata[] = [
    //                 'path'        => $path,
    //                 'create_time' => $this->request->time(),
    //                 'sha1'        => $res->hash(),
    //                 'size'        => $getid3['filesize'],
    //                 'mime'        => $getid3['mime_type'],
    //                 'ext'         => $getid3['fileformat'],
    //                 'playtime'    => $getid3['playtime_string'],
    //             ];
    //             //压缩mp3
    //             $temp_path = $this->config['temp_path'] . DS . substr($res->hash(), 0, 2);
    //             mkdirs($temp_path); //创建目录
    //             $temp_paths = $temp_path . DS . '128_' . $res->hash() . '.mp3'; //压缩输出完整根路径
    //             ffmpeg($path, $temp_paths); //压缩mp3
    //         }
    //         $data[] = $file->hash();
    //     }
    //     if (!empty($savedata)) {
    //         db('file')->insertAll($savedata);
    //     }
    //     return $this->response('上传成功!', 200, $data);
    // }

    /**
     * 文件上传(断点续传)
     */
    public function uploads($part, $sha1) {
        
    }

}
